package com.nulp.psycho.web.servlet.interpretation;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nulp.psycho.db.model.Interpretation;
import com.nulp.psycho.db.model.Result;
import com.nulp.psycho.db.model.User;
import com.nulp.psycho.db.service.InterpretationService;
import com.nulp.psycho.db.service.ResultService;


public class BemTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int f = 0;
		int m = 0;
		int is = 0;
		
		@SuppressWarnings("unchecked")
		List<String> ans =  (List<String>) request.getAttribute("answers");
		int testId = Integer.parseInt(request.getParameter("testIdid"));
		User user = (User) request.getSession(true).getAttribute("user");
		
		
		for (int i = 0; i < ans.size(); i++) {
			
			if((i==0)||(i==3)||(i==6)||(i==9)||(i==12)||(i==15)||(i==18)||(i==21)||(i==24)||(i==27)||(i==30)||(i==33)||(i==36)||(i==39)||(i==42)||(i==45)||(i==48)||(i==51)||(i==54)||(i==57)){
				if(ans.get(i).equals("Так")){
					m++;
				}
			}
			
			if ((i==1)||(i==4)||(i==7)||(i==10)||(i==13)||(i==16)||(i==19)||(i==22)||(i==25)||(i==28)||(i==31)||(i==34)||(i==37)||(i==40)||(i==43)||(i==46)||(i==49)||(i==52)||(i==55)||(i==58)) {
				if(ans.get(i).equals("Так")){
					f++;
				}
			}
		}
		
		is = (f-m)*2322;
		
		
		ResultService service = new ResultService();
		Result res = new Result();
		res.setParam("is");
		res.setValue(is);
		res.setTestId(testId);
		res.setUserId(user.getId());		
		service.create(res);
		
		
		Interpretation interpretation = new Interpretation();
		interpretation = new InterpretationService().getInterpretationByValue("is", is);
		request.setAttribute("isExp", interpretation.getExplanation());
		request.setAttribute("isText", interpretation.getText());
		
		request.setAttribute("is", is);
		request.getRequestDispatcher("WEB-INF/pages/results/bemResult.jsp").forward(request, response);
		
	}

}
